﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Realize;
using Dapper;
using System.ComponentModel.Design;
using IRealize;
using Entity;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace WebApplication9.Controllers.HRFA
{
    public class HRFRController : Controller
    {
        private readonly IConfiguration configuration;
        private readonly ILogger<HRFRController> _logger;
        private readonly IWebHostEnvironment _environment;

        public HRFRController(IConfiguration configuration, ILogger<HRFRController> logger, IWebHostEnvironment webHostEnvironment)
        {
            this.configuration = configuration;
            _logger = logger;
            this._environment= webHostEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevelCXJL")]
        public async Task<IActionResult> FirstLevelCXJL()
        {

            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS id, first_kind_name AS name 
              FROM config_file_first_kind 
              WHERE first_kind_id IS NOT NULL AND first_kind_name IS NOT NULL");


                // 2. 查询II级机构
                var secondKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT first_kind_id AS parentId, 
                     second_kind_id AS id, 
                     second_kind_name AS name 
              FROM config_file_second_kind 
              WHERE second_kind_id IS NOT NULL AND second_kind_name IS NOT NULL");


                // 3. 查询III级机构
                var thirdKinds = await connection.QueryAsync<dynamic>(
                    @"SELECT second_kind_id AS parentId, 
                     third_kind_id AS id, 
                     third_kind_name AS name 
              FROM config_file_third_kind 
              WHERE third_kind_id IS NOT NULL AND third_kind_name IS NOT NULL");

                // 4. 构建级联数据（使用实体类）
                var result = new List<CascaderNode>();

                foreach (var first in firstKinds)
                {
                    var firstId = first.id;
                    var seconds = secondKinds.Where(s => s.parentId == firstId).ToList();

                    var secondList = new List<CascaderNode>(); // 明确为CascaderNode列表

                    foreach (var second in seconds)
                    {
                        var secondId = second.id;
                        // 构建III级节点（实体类）
                        var thirds = thirdKinds
                            .Where(t => t.parentId == secondId)
                            .Select(t => new CascaderNode
                            {  // 使用实体类
                                id = t.id,
                                name = t.name,
                                children = new List<CascaderNode>() // 子节点也是实体类列表
                            })
                            .ToList();

                        // 构建II级节点（实体类），此时thirds和空列表类型一致
                        secondList.Add(new CascaderNode
                        {
                            id = second.id,
                            name = second.name,
                            children = thirds.Any() ? thirds : new List<CascaderNode>() // 都是List<CascaderNode>
                        });
                    }

                    // 构建I级节点（实体类）
                    result.Add(new CascaderNode
                    {
                        id = first.id,
                        name = first.name,
                        children = secondList.Any() ? secondList : new List<CascaderNode>() // 类型一致
                    });
                }

                return Ok(result);
            }

        }

        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevel")]
        public async Task<IActionResult> FirstLevel()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    "SELECT first_kind_id AS id, first_kind_name AS name FROM config_file_first_kind");

                // 构建级联数据结构
                var result = new List<dynamic>();

                foreach (var firstKind in firstKinds)
                {
                    // 查询对应的II级机构
                    var secondKinds = await connection.QueryAsync<dynamic>(
                        "SELECT second_kind_id AS id, second_kind_name AS name " +
                        "FROM config_file_second_kind " +
                        "WHERE first_kind_id = @Id",
                        new { Id = firstKind.id });

                    var secondList = new List<dynamic>();


                    // 在构建二级机构时，确保children为非空数组
                    foreach (var secondKind in secondKinds)
                    {
                        var thirdKinds = await connection.QueryAsync<dynamic>(
                            "SELECT third_kind_id AS id, third_kind_name AS name " +
                            "FROM config_file_third_kind " +
                            "WHERE second_kind_id = @Id",
                            new { Id = secondKind.id });

                        // 显式转换为List，避免空枚举导致前端渲染异常
                        secondList.Add(new
                        {
                            id = secondKind.id,
                            name = secondKind.name,
                            children = thirdKinds.ToList() // 确保children为非空数组（即使无数据）
                        });
                    }

                    // 处理一级机构无二级机构的情况
                    result.Add(new
                    {
                        id = firstKind.id,
                        name = firstKind.name,
                        children = secondList.Any() ? secondList : new List<dynamic>() // 空数组处理
                    });
                    
                }

                return Ok(result);
            }
        }



        // 新增获取性别选项的接口
        [HttpGet("GetGenderOptions")]
        public async Task<IActionResult> GetGenderOptions()
        {
            try
            {
                // 实例化接口实现类
                IRLXLK rlxlk = new RLXLK();
                // 调用 CXXLK 方法（假设 human_file 表中包含性别数据）
                var humanFiles = await rlxlk.CXXLK(configuration["SqlServer"]);

                return Ok(humanFiles);
            }
            catch (Exception ex)
            {
                return StatusCode(500, "获取下拉框数据失败：" + ex.Message);
            }
        }



     
        public async Task<IActionResult> Add([FromBody] Human_File model)
        {
            try
            {
                if (model == null)
                {
                    return BadRequest(new { code = 400, msg = "请求数据为空" });
                }

                RLXLK rLXLK = new RLXLK();
                int rowsAffected = await rLXLK.AddHF(model, configuration["SqlServer"]);

                if (rowsAffected > 0)
                {
                    return Ok(new { success = true, message = "添加成功" });
                }
                else
                {
                    return BadRequest(new { success = false, message = "添加失败" });
                }        
            }
            catch (Exception ex)
            {
                // 记录完整异常信息（包括堆栈跟踪）
                Console.WriteLine($"新增档案失败: {ex.Message}\n{ex.StackTrace}");
                return StatusCode(500, new { code = 500, msg = "服务器内部错误: " + ex.Message });
            }
        }



        public IActionResult Success()
        {
            return View();
        }




        public IActionResult RLFH()
        {
            return View();
        }


        public IActionResult RLFHCX(int pageSize,int currentPage)
        {
            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "huf_id");
                param.Add("@tableName", "human_file");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Human_File> list = conn.Query<Human_File>(sql, param).ToList();
                List<Human_File> list2 = list.Where(e => e.check_status == 0).ToList(); ;
                FenYe<Human_File> fenYecs = new FenYe<Human_File>();
                fenYecs.List = list2;
                fenYecs.Rows = param.Get<int>("totalRows");
                return Json(fenYecs);

            }

        }


        //薪酬标准下拉框绑定数据
        public async Task<IActionResult> GetSalaryStandards()
        {
            IRLXLK rLXLK = new RLXLK();

            var salaryStandards = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = salaryStandards.Select(s => new
            {
                value = s.salary_standard_id,
                label = s.salary_standard_name
            }).ToList();
            return Ok(options);
        }



        //薪酬标准下拉框绑定数据
        public async Task<IActionResult> GetSalaryStandardsED()
        {
            IRLXLK rLXLK = new RLXLK();

            var salaryStandards = await rLXLK.CXXCXLK(configuration["SqlServer"]);
            var options = salaryStandards.Select(s => new
            {
                value = s.standard_id,
                label = s.standard_name,
                salarySum = s.salary_sum.ToString()  // 基本薪酬总额（新增字段）
            }).ToList();
            return Ok(options);
        }


        //职位分类
        public async Task<IActionResult> Jofl()
        {
            IRLXLK rLXLK = new RLXLK();

            var fl = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = fl.Select(s => new
            {
                value = s.human_major_kind_id,
                label = s.human_major_kind_name
            }).ToList();
            return Ok(options);
        }

        //职位名称
        public async Task<IActionResult> Jomc()
        {
            IRLXLK rLXLK = new RLXLK();

            var mc = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = mc.Select(s => new
            {
                value = s.human_major_id,
                label = s.hunma_major_name
            }).ToList();
            return Ok(options);
        }

        //性别下拉框绑定数据
        public async Task<IActionResult> Sex()
        {
            IRLXLK rLXLK = new RLXLK();

            var sex = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = sex.Select(s => new
            {
                value = s.human_sex,
                label = s.human_sex
            }).ToList();
            return Ok(options);
        }

        //获取职称
        public async Task<IActionResult> ZhiChen()
        {
            IRLXLK rLXLK = new RLXLK();

            var zhicheng = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = zhicheng.Select(s => new
            {
                value = s.human_pro_designation,
                label = s.human_pro_designation
            }).ToList();
            return Ok(options);
        }

        //获取国籍
        public async Task<IActionResult> nation()
        {
            IRLXLK rLXLK = new RLXLK();

            var nation = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = nation.Select(s => new
            {
                value = s.human_nationality,
                label = s.human_nationality
            }).ToList();
            return Ok(options);
        }

        //获取民族
        public async Task<IActionResult> Race()
        {
            IRLXLK rLXLK = new RLXLK();

            var race = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = race.Select(s => new
            {
                value = s.human_race,
                label = s.human_race
            }).ToList();
            return Ok(options);
        }

        //获取宗教信仰
        public async Task<IActionResult> Religion()
        {
            IRLXLK rLXLK = new RLXLK();

            var religion = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = religion.Select(s => new
            {
                value = s.human_religion,
                label = s.human_religion
            }).ToList();
            return Ok(options);
        }


        //获取政治面貌
        public async Task<IActionResult> Party()
        {
            IRLXLK rLXLK = new RLXLK();

            var party = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = party.Select(s => new
            {
                value = s.human_party,
                label = s.human_party
            }).ToList();
            return Ok(options);
        }

        //获取学历下拉框数据
        public async Task<IActionResult> Drgerr()
        {
            IRLXLK rLXLK = new RLXLK();

            var degree = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = degree.Select(s => new
            {
                value = s.human_educated_degree,
                label = s.human_educated_degree
            }).ToList();
            return Ok(options);
        }

        //获取教育年限
        public async Task<IActionResult> Years()
        {
            IRLXLK rLXLK = new RLXLK();

            var ysears = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = ysears.Select(s => new
            {
                value = s.human_educated_years,
                label = s.human_educated_years
            }).ToList();
            return Ok(options);
        }


        //获取专业名称
        public async Task<IActionResult> Majorname()
        {
            IRLXLK rLXLK = new RLXLK();

            var major = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = major.Select(s => new
            {
                value = s.human_educated_major,
                label = s.human_educated_major
            }).ToList();
            return Ok(options);
        }

        //获取特长
        public async Task<IActionResult> Speciality()
        {
            IRLXLK rLXLK = new RLXLK();

            var party = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = party.Select(s => new
            {
                value = s.human_speciality,
                label = s.human_speciality
            }).ToList();
            return Ok(options);
        }

        //获取爱好
        public async Task<IActionResult> Hobby()
        {
            IRLXLK rLXLK = new RLXLK();

            var hobby = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = hobby.Select(s => new
            {
                value = s.human_hobby,
                label = s.human_hobby
            }).ToList();
            return Ok(options);
        }

        //获取职位分类
        public async Task<IActionResult> JobRY()
        {
            IRLXLK rLXLK = new RLXLK();

            var job1 = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = job1.Select(s => new
            {
                value = s.human_major_kind_id,
                label = s.human_major_kind_name
            }).ToList();
            return Ok(options);
        }

        //获取职位名称
        public async Task<IActionResult> JobNamecx()
        {
            IRLXLK rLXLK = new RLXLK();

            var job2 = await rLXLK.CXXLK(configuration["SqlServer"]);
            var options = job2.Select(s => new
            {
                value = s.human_major_id,
                label = s.hunma_major_name
            }).ToList();
            return Ok(options);
        }







        //根据主键查询信息
        public async Task<IActionResult> Update(int id)
        {
            return View();
        }

        public async Task<IActionResult> CXFH(int id)
        {
            IRLXLK rLXLK = new RLXLK();
            Human_File fileDig = await rLXLK.SelectHFIDAsync(id, configuration["SqlServer"]);


            // 映射数据为前端需要的格式，包含原机构和原职位ID
            var result = new
            {
                success = true,
                data = new
                {

                    huf_id = fileDig.huf_id,
                    human_id = fileDig.human_id,
                    human_name = fileDig.human_name,
                    human_id_card = fileDig.human_id_card,
                    first_kind_name = fileDig.first_kind_name,
                    second_kind_name = fileDig.second_kind_name,
                    third_kind_name = fileDig.third_kind_name,
                    human_major_kind_name = fileDig.human_major_kind_name,
                    hunma_major_name = fileDig.hunma_major_name,
                    human_pro_designation = fileDig.human_pro_designation,
                    human_sex = fileDig.human_sex,
                    human_email = fileDig.human_email,
                    human_mobilephone = fileDig.human_mobilephone,
                    human_qq = fileDig.human_qq,
                    human_telephone = fileDig.human_telephone,
                    human_address = fileDig.human_address,
                    human_postcode = fileDig.human_postcode,
                    human_nationality = fileDig.human_nationality,
                    human_birthplace = fileDig.human_birthplace,
                    human_birthday = fileDig.human_birthday,
                    human_race = fileDig.human_race,
                    human_religion = fileDig.human_religion,
                    human_party = fileDig.human_party,
                    human_society_security_id = fileDig.human_society_security_id,
                    human_age = fileDig.human_age,
                    human_educated_degree = fileDig.human_educated_degree,
                    human_educated_years = fileDig.human_educated_years,
                    human_educated_major = fileDig.human_educated_major,
                    salary_standard_name = fileDig.salary_standard_name,
                    human_bank = fileDig.human_bank,
                    human_account = fileDig.human_account,

                    checker = fileDig.checker,

                    //拿到复核人
                    checkrName = HttpContext.Session.GetString("PName"),

                    check_time = fileDig.check_time,
                    human_speciality = fileDig.human_speciality,
                    human_hobby = fileDig.human_hobby,
                    attachment_name = fileDig.attachment_name,
                    human_histroy_records = fileDig.human_histroy_records,
                    human_family_membership = fileDig.human_family_membership,
                    remark = fileDig.remark,
                    human_picture = fileDig.human_picture,



                }
            };

            return Ok(result);

        }


        public async Task<IActionResult> UpdateHR([FromBody] Human_File human_File)
        {
            IRLXLK dDGLD = new RLXLK();


            // 调用AddHF方法
            int result = await dDGLD.Update1HFAsync(human_File, configuration["SqlServer"]);

            if (result > 0)
            {
                return Ok(new { success = true, message = "添加成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "添加失败" });
            }

        }

        public async Task<IActionResult> UpdateBTG([FromBody] Human_File human_File)
        {
            IRLXLK dDGLD = new RLXLK();


            // 调用AddHF方法
            int result = await dDGLD.UpdateHFBTGAsync(human_File, configuration["SqlServer"]);

            if (result > 0)
            {
                return Ok(new { success = true, message = "复核不通过提交成功" });
            }
            else
            {
                return BadRequest(new { success = false, message = "复核不通过提交失败" });
            }

        }



        [HttpPost]
        public IActionResult WJSC(IFormFileCollection file)
        {


            foreach (var item in file)
            {
                if (item.Length > 0)
                {
                    try
                    {
                        // 获取文件扩展名
                        string ext = Path.GetExtension(item.FileName);

                        // 生成唯一文件名
                        string fileName = $"{DateTime.Now:yyyyMMddHHmmssfff}{ext}";

                        // 定义层级文件夹路径
                        string folderPath = Path.Combine(
                            _environment.WebRootPath,
                            "Uploader",
                            DateTime.Now.ToString("yyyy"),
                            DateTime.Now.ToString("MM"),
                            DateTime.Now.ToString("dd")
                        );

                        // 确保文件夹存在
                        Directory.CreateDirectory(folderPath);

                        // 生成完整文件路径
                        string filePath = Path.Combine(folderPath, fileName);

                        // 保存文件
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            item.CopyTo(stream);
                        }

                        return Ok(new
                        {
                            success = true,
                            wjnames = fileName, // 返回文件名      
                            filePath = $"/Uploader/{DateTime.Now:yyyy/MM/dd}/{fileName}" // 返回可访问的相对路径
                        });

                    }catch (Exception ex)
                    {
                        _logger.LogError(ex, "文件上传失败");
                        return StatusCode(500, new { success = false, message = "上传文件时发生错误" });
                    }
                }
            }

            return Json(new { success = false, message = "未选择文件" });

            

        }

        [HttpPost]
        public async Task<IActionResult> Update(int id,Human_File model,string imageFileName)
        {
            model.human_picture = imageFileName;
            model.check_time = DateTime.Now;

            RLXLK rLXLK = new RLXLK();
            int js =await rLXLK.UpdateHFAsync(model, configuration["SqlServer"], id);

            if (js > 0)
            {
                return RedirectToAction("RLFH");
            }
            else
            {
                return View();
            }

        }



        [HttpGet("JobCategoryCXDD")]
        public async Task<IActionResult> JobCategoryCXDD()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 1. 查询所有职位分类（第1级）
                var categories = await connection.QueryAsync<dynamic>(
                    @"SELECT major_kind_id AS id, major_kind_name AS name 
              FROM config_major_kind");

                // 2. 查询所有职位（第2级）
                var jobs = await connection.QueryAsync<dynamic>(
                    @"SELECT major_kind_id AS parentId, major_id AS id, major_name AS name 
              FROM config_major");

                // 3. 构建级联数据（使用实体类）
                var result = new List<CascaderNode>();

                foreach (var category in categories)
                {
                    var categoryId = category.id;
                    var categoryJobs = jobs.Where(j => j.parentId == categoryId).ToList();

                    // 构建职位列表（第2级节点）
                    var jobList = categoryJobs.Select(job => new CascaderNode
                    {
                        id = job.id,
                        name = job.name,
                        children = new List<CascaderNode>() // 确保children存在
                    }).ToList();

                    // 构建职位分类节点（第1级节点）
                    result.Add(new CascaderNode
                    {
                        id = category.id,
                        name = category.name,
                        children = jobList.Any() ? jobList : new List<CascaderNode>()
                    });
                }

                return Ok(result);
            }
        }





      
        public IActionResult GetRegistrant()
        {
            // 从Session中获取PName
            var registrant = HttpContext.Session.GetString("PName");
            if (string.IsNullOrEmpty(registrant))
            {
                return Ok(new { success = false, message = "未获取到登记人信息" });
            }
            return Ok(new { success = true, registrant = registrant });
        }




    }
}
